import { defineStore } from 'pinia';
import api from "@/api/index.js";

export const useMyNeedsStore = defineStore('MyNeeds', {
	state: () => {
		return {
			params: {
				name: '',
				limit: 20,
				page: 1,
			},
			total: 0,
			list: [],

			loadingState: {
				default: false,
				loading: false,
				stop: false,
				pullup: false,
			}
		}
	},

	getters: {

	},

	actions: {
		// 重置store
		RESET_STORE() {
			this.$reset();
		},

		/**
		 * 设置参数
		 * @param {String} field 字段名
		 * @param {Any} value 字段值
		 * @param {Boolean} isSearch 是否为搜索
		 */
		SET_PARAMS(field, value, isSearch = false) {
			if (!this.params.hasOwnProperty(field)) return;
			this.params[field] = value;
			if (isSearch) {
				this.refreshList();
			} else {
				this.getList();
			}
		},

		// 刷新页面数据
		refreshList() {
			this.params.page = 1;
			this.getList();
		},

		// 获取列表数据
		async getList() {
			// 正在加载中并且不是第一页，或者已经加载完所有了
			if ((this.loadingState.default && this.params.page !== 1) || (this.loadingState.stop && this
					.params.page > 1)) return;
			this.loadingState.default = true;
			this.loadingState.pullup = false;
			this.loadingState.stop = false;

			const res = await api.c_need_api.getList(this.params);

			this.total = res.data.data.totals;
			const list = res.data.data.list;

			if (this.params.page === 1) {
				this.list = list;
			} else {
				this.list.push(...list);
			}

			this.loadingState.default = false;
			if (this.list.length < this.total) {
				this.loadingState.pullup = true;
			} else if (this.total === 0) {
				this.loadingState.stop = false;
			} else {
				this.loadingState.stop = true;
			}

			this.params.page += 1;
		}
	},
})